<?php
namespace app\admin\controller;
use think\Controller;
use Firebase\JWT\JWT;

class Login extends Controller
{
    public function __construct()
    {
        header("Access-Control-Allow-Origin: *");//允许跨域
        header('Content-type: application/json');
        header("Access-Control-Allow-Methods:POST");
        header("Access-Control-Allow-Credentials: true");
        header("access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept,WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,authorization");

        if (!request()->isPost()) {
            echo refuseVisit();die;
        }
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $data = input('post.');

        $data['account']     = htmlspecialchars($data['account']);
        $data['password']       = htmlspecialchars($data['password']);

        //校验数据
        $validate = \think\Loader::validate('Login');
        if(!$validate->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        //验证账号
        $row = db('admin',[],false)->where('ad_account',$data['account'])->find();

        if ($row) {
            //验证密码
            if ($row['ad_pwd'] == md5($data['password'].'SecretAdmin')) {
                $info['code']    = '200';
                $info['message'] = '登录成功';
                $info['id']      = $row['ad_id'];
                $info['account'] = $row['ad_account'];
                $info['email']   = $row['ad_email'];
                $info['jwt']     = self::createJwt($row['ad_id']);  //生成jwt
                echo displayJson($info);die;
            } else {
                $info['code']    = '400';
                $info['message'] = '密码错误';
                echo displayJson($info);die;
            }
        } else {
            $info['code']    = '400';
            $info['message'] = '该用户不存在';
            echo displayJson($info);die;
        }
    }

    /**
     * 生成jwt
     * @param $userId
     * @return string
     */
    public function createJwt($userId)
    {
        $key    = md5('taoerhuo'); //jwt的签发密钥，验证token的时候需要用到
        $time   = time(); //签发时间
        $expire = $time + 604800; //过期时间(一天)
        $token  = array(
            "us_id" => $userId,
            "iss" => "http://glyxi.com",//签发组织
            "aud" => "YeWenHao", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );

        $jwt = JWT::encode($token, $key);
        return $jwt;
    }

}
